package com.aichan.aibi.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.aichan.aibi.annotation.TimeConsume;
import com.aichan.aibi.common.BaseResponse;
import com.aichan.aibi.common.DeleteRequest;
import com.aichan.aibi.common.ErrorCode;
import com.aichan.aibi.exception.BusinessException;
import com.aichan.aibi.exception.ThrowUtils;
import com.aichan.aibi.model.dto.user.*;
import com.aichan.aibi.model.entity.User;
import com.aichan.aibi.model.vo.LoginUserVO;
import com.aichan.aibi.model.vo.UserVO;
import com.aichan.aibi.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * @author mengyu
 * @date 2024/03/03 9:40
 * 用户接口
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @TimeConsume
//    @PreAuthorize("hasAnyRole('admin')")
    @GetMapping("/hello")
    public String hello() throws InterruptedException {
        Thread.sleep(500);
        return "hello";
    }

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@Valid @RequestBody UserRegisterRequest userRegisterRequest) {
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return BaseResponse.ok(result);
    }

    @PostMapping("/login")
    BaseResponse<LoginUserVO> userLogin(@Valid @RequestBody UserLoginRequest userLoginRequest) {
        return BaseResponse.ok(userService.userLogin(userLoginRequest.getUserAccount(), userLoginRequest.getUserPassword()));
    }

    @PostMapping("/forget")
    BaseResponse<Long> forgetPassword(@Valid @RequestBody UserForgetPasswordRequest userForgetPasswordRequest) {
        String email = userForgetPasswordRequest.getEmail();
        String password = userForgetPasswordRequest.getPassword();
        String checkPassword = userForgetPasswordRequest.getCheckPassword();
        Integer code = userForgetPasswordRequest.getCode();
        Long l = userService.userForgetPassword(email, password, checkPassword, code);
        return BaseResponse.ok(l);
    }

    /**
     * 用户注销
     *
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout() {
        userService.logout();
        return BaseResponse.ok(null);
    }

    /**
     * 获取当前登录用户
     *
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        String token = request.getHeader("token");
        return BaseResponse.ok(userService.getLoginUserVO(token));
    }

    /**
     * 创建用户
     *
     * @param userAddRequest
     * @return
     */
    @PostMapping("/add")
    @PreAuthorize("hasAnyRole('admin')")
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        String userAccount = userAddRequest.getUserAccount();
        String password = userAddRequest.getPassword();
        String email = userAddRequest.getEmail();
        String userRole = userAddRequest.getUserRole();
        User user = userService.addUser(userAccount, password, email, userRole);
        return BaseResponse.ok(user.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @PreAuthorize("hasAnyRole('admin')")
    public BaseResponse<Boolean> deleteUser(@Valid @RequestBody DeleteRequest deleteRequest) {
        userService.deleteUser(deleteRequest.getId());
        return BaseResponse.ok(true);
    }

    /**
     * 更新用户 （管理员）
     *
     * @param userUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAnyRole('admin')")
    public BaseResponse<Boolean> updateUser(@Valid @RequestBody UserUpdateRequest userUpdateRequest) {
        userService.updateUser(userUpdateRequest);
        return BaseResponse.ok(true);
    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    @PreAuthorize("hasAnyRole('admin')")
    public BaseResponse<User> getUserById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return BaseResponse.ok(user);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id, HttpServletRequest request) {
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return BaseResponse.ok(UserVO.getUserVO(user));
    }

    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param userQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @PreAuthorize("hasAnyRole('admin')")
    public BaseResponse<Page<User>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest) {
        Long id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        String userRole = userQueryRequest.getUserRole();
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        LambdaQueryWrapper<User> ulqw = new LambdaQueryWrapper<>();
        ulqw.eq(id != null, User::getId, id)
                .like(!StrUtil.isBlankIfStr(userName), User::getUserName, userName)
                .eq(!StrUtil.isBlankIfStr(userRole), User::getUserRole, userRole);
        Page<User> userPage = userService.page(new Page<>(current, size),
                ulqw);
        return BaseResponse.ok(userPage);
    }


    /**
     * 更新个人信息
     *
     * @param userUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    public BaseResponse<Boolean> updateMyUser(@RequestBody UserUpdateMyRequest userUpdateMyRequest,
                                              HttpServletRequest request) {
        if (userUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        User user = new User();
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(loginUser.getId());
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return BaseResponse.ok(true);
    }
}
